<?php

namespace process;

use app\model\User;
use library\wechat;
use support\Log;
use Workerman\Crontab\Crontab;

class Task
{
    public function onWorkerStart()
    {
        // 每天凌晨 1 点执行
        new Crontab('0 1 * * *', function () {
            Log::info('开始执行订阅消息过期提醒任务');

            $user_list = User::where('status', 1)->where('')->select();
            foreach ($user_list as $user) {
                try {
                    $data = [
                        'thing2' => ['value' => '【官方】系统提示'],
                        'time3'  => ['value' => date('Y-m-d H:i:s')],
                        'thing4' => ['value' => '一次性订阅消息已过期，请重新订阅'],
                    ];
                    $templateId = env('WECHAT_TEMPLATE');
                    $page = 'pages/index/index';

                    $res = wechat::send_message($user->openid, $templateId, $page, $data);

                    if ($res['errcode'] != 0) {
                        Log::warning("推送失败：{$user->openid} - {$res['errmsg']}");
                    } else {
                        Log::info("推送成功：{$user->openid}");
                    }
                } catch (\Throwable $e) {
                    Log::error("异常推送用户：{$user->openid}，错误：{$e->getMessage()}");
                }
            }

            Log::info('订阅消息过期提醒任务执行完毕');
        });

        // 每分钟执行一次
        // ✅ 每分钟执行一次：释放过期分机号
        new Crontab('* * * * *', function () {
            try {
                \app\service\DnService::cleanupExpired();
            } catch (\Throwable $e) {
                Log::error('定时释放过期分机号失败：' . $e->getMessage());
            }
        });



    }
}
